<template>
  <div>
    <list ref="list"
          :showRefresh="true"
          :showLoadMore="showLoadMore"
          @refresh="refresh"
          @loadMore="loadmore"
          loadmoreoffset="100">
      <cell v-for="(task, index) in tasks"
            :key="index">
        <div class="flex-row bg-white border-bottom-light"
             @click="goTask(task)">
          <text class="td-task">{{task.createTime}}</text>
          <text class="td-task">{{task.taskName}}</text>
          <text class="td-task"
                :class="[task.stautsStyle]">{{task.statusName}}</text>
        </div>
      </cell>
      <cell v-if="showStatus">
        <vm-status empty-text="没有任务~"
                   error-text="获取任务失败"
                   :show-button="isError"
                   :type="isError ? 'error' : 'empty'"
                   @buttonClicked="getTask(true)"></vm-status>
      </cell>
      <cell v-else-if="!showLoadMore">
        <text class="nomore-text">---- 没有更多任务 ----</text>
      </cell>
    </list>
  </div>
</template>
<script>
import VmStatus from '../../components/vm-status.vue'
import {
  STORAGE_FARM
} from '../../plugins/constant'
import {
  enumTask,
  enumTaskRouter
} from '../../plugins/enumChick'

export default {
  components: { VmStatus },
  props: {},
  data() {
    return {
      farm: {},
      params: {
        index: 1,
        size: 20,
        'task_person.eq': '',
        'task_status.eq': 1
      },
      tasks: [],
      totalPages: 2,
      isError: false,
      hasFetch: false
    }
  },
  computed: {
    showLoadMore() {
      return this.totalPages > this.params.index
    },
    showStatus() {
      return this.isError || (this.hasFetch && !this.tasks.length)
    }
  },
  watch: {},
  created() {
    this.getFarm()
  },
  methods: {
    getFarm() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      if (this.farm.id) {
        this.refresh()
      } else {
        this.hasFetch = true
        this.$notice.toast({ message: '没有鸡场信息' })
        this.$router.setBackParams({ type: 1 })
      }
    },
    refresh() {
      this.params.index = 1
      this.getTask().then(res => {
        this.tasks = res
      }).finally(() => this.$refs["list"].refreshEnd())
    },
    loadmore() {
      if (!this.showLoadMore) {
        return this.$refs["list"].loadMoreEnd()
      }
      this.params.index += 1
      this.getTask().then(res => {
        this.tasks.push(...res)
      }).finally(() => this.$refs["list"].loadMoreEnd())
    },
    getTask() {
      return new Promise((resolve, reject) => {
        this.params['task_person.eq'] = this.farm.id
        this.$api.getData({
          server: 'agr_chain',
          table: 'task_list',
          params: this.params,
          order: {
            create_time: 'desc'
          },
          errorMsg: '任务获取失败'
        }).then(res => {
          this.totalPages = res && res.totalPages || 0
          const data = res && res.data || []
          resolve(data.map(item => {
            item.createTime = this.$utils.dateFormat(item.create_time, 'yyyy.MM.dd')
            item.taskName = enumTask[item.task_type] || '其他任务'

            const noFinish = +item.task_status === 0
            item.statusName = noFinish ? '未处理' : '已处理'
            item.stautsStyle = noFinish ? 'text-warning' : 'text-success'
            // 已超时标红色 -> 6点前未处理标红色
            const nowDate = this.$utils.dateFormat(new Date(), 'yyyy.MM.dd')
            if (noFinish && nowDate !== item.createTime || new Date().getHours() >= 18) {
              item.stautsStyle = 'text-error'
            }
            return item
          }))
        }).catch(err => {
          this.isError = true
          reject(err)
        }).finally(() => this.hasFetch = true)
      })
    },
    goTask(task) {
      const type = enumTaskRouter[task.task_type]
      if (!type) { return }
      this.$nav.open({
        name: type,
        params: {
          task,
          viewMode: true
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.p-2 {
  padding: 20px;
}
.bg-white {
  background-color: #fff;
}
.text-normal {
  font-size: 28px;
}
.text-muted {
  color: #999;
}
.text-warning {
  color: $warning;
}
.text-error {
  color: $error;
}
.text-success {
  color: $success;
}
.flex-row {
  flex-direction: row;
}
.td-task {
  flex: 1;
  font-size: 28px;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 25px;
  padding-bottom: 25px;
  text-align: center;
}
.nomore-text {
  padding: 30px;
  font-size: 22px;
  text-align: center;
  color: #999;
}
</style>
